from typing import Union

from fastapi import HTTPException, status

from app.models.account_models import Account
from app.schemas.accounts_schemas import EditAccountRequestSchema
from app.schemas.auth_schemas import RegistrationRequestSchema
from app.tools.email_validator import validate_user_email


class AccountTools:
    """Класс предназначенный для соблюдения метода DRY при работе
    с пользователями"""

    @staticmethod
    def check_account_id_is_valid(account_id: int):
        """Метод для проверки корректности id пользователя"""
        if account_id is None or account_id <= 0:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    def validate_account_request(
        request: Union[EditAccountRequestSchema | RegistrationRequestSchema],
    ):
        """Метод отвечающий за валидацию запроса на создание/редактирования аккаунта"""
        if (
            request.firstName.isspace()
            or request.firstName is None
            or request.firstName == ""
        ):
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
        if (
            request.lastName.isspace()
            or request.lastName is None
            or request.lastName == ""
        ):
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
        if (
            request.email.isspace()
            or request.email is None
            or request.email == ""
            or not validate_user_email(request.email)
        ):
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
        if (
            request.password.isspace()
            or request.password is None
            or request.password == ""
        ):
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    async def check_email_conflict(email: str):
        """Метод отвечающий за проверку наличия аккаунта с такой же почтой в базе"""
        users = await Account.filter(email=email)

        if len(users) != 0:
            raise HTTPException(status_code=status.HTTP_409_CONFLICT)

    @staticmethod
    async def create_admin():
        admin = await Account.get_or_none(id=1)
        if admin is None:
            await Account.create(
                firstName="admin",
                lastName="admin",
                email="admin",
                password="admin"
            )
